import { _decorator, Component, Label, Node, Prefab, Vec3 } from 'cc';
import { PoolManager } from './PoolManager';
import { MoveItem } from './MoveItem';
const { ccclass, property } = _decorator;

@ccclass('MoveItemManager')
export class MoveItemManager extends Component {
    public static Instance: MoveItemManager = null;

    @property(Prefab)
    ItemPrefab: Prefab = null;

    @property(Node)
    Ball: Node = null;

    @property(Label)
    ScoreLabel: Label = null;

    @property
    lifetime: number = 5;

    @property
    InvincibleTime: number = 0.1;

    @property
    speed: number = 5;

    @property
    Interval: number = 1;

    @property
    StartNum: number = 1;

    @property
    AddNum: number = 1;

    private _timer: number = 0;
    private _createTimer: number = 0;
    private _initPos: Vec3;
    private _count: number = 0;
    private _interval: number = 0.01;
    private _score: number = 0;

    protected onLoad(): void {
        MoveItemManager.Instance = this;
    }

    protected start(): void {
        this._initPos = this.node.getWorldPosition();
        this.createItems(this.StartNum);
        PoolManager.Instance.preload(this.ItemPrefab, 10000);
        this.showScore();
    }

    protected update(dt: number): void {
        this._timer += dt;
        this._createTimer += dt;

        if (this._timer > this.Interval) {
            this._timer = 0;
            this.StartNum += this.AddNum;
            this.createItems(this.StartNum);
        }

        if (this._createTimer > this._interval && this._count > 0) {
            this._createTimer = 0;
            this._count--;
            this.createItem();
        }
    }

    // createItems(count: number) {
    //     for (let i = 0; i < count; i++) {
    //         this.createItem();
    //     }
    // }

    createItems(count: number) {
        this._count += count;
    }

    createItem() {
        const node: Node = PoolManager.Instance.get(this.ItemPrefab);
        node.getComponent(MoveItem).init(this.node, this._initPos, this.lifetime, this.InvincibleTime, this.speed);
    }

    getDis(other: Node): number {
        return Vec3.distance(this.Ball.getWorldPosition(), other.getWorldPosition());
    }

    private showScore() {
        this.ScoreLabel.string = "分数：" + this._score.toString();
    }

    addScore() {
        this._score++;
        this.showScore();
    }
}


